import React, { useState } from 'react'
import { View, Text } from '@tarojs/components'
import { Navbar, Form, Input, Button, Radio, Cell, Slider, Dialog, Divider } from '@taroify/core'
import { ArrowLeft } from '@taroify/icons'
import Taro from '@tarojs/taro'
import './index.scss'

const LoanCalculator = () => {
  const [loanAmount, setLoanAmount] = useState('')
  const [loanTerm, setLoanTerm] = useState(30)
  const [interestRate, setInterestRate] = useState(4.9)
  const [repaymentMethod, setRepaymentMethod] = useState('equal-principal-interest')
  const [result, setResult] = useState(null)

  const handleBack = () => {
    Taro.navigateBack()
  }

  const calculate = () => {
    if (!loanAmount || loanAmount <= 0) {
      Dialog.alert({
        title: '提示',
        message: '请输入有效的贷款金额'
      })
      return
    }

    const principal = parseFloat(loanAmount) * 10000 // 转换为元
    const years = parseInt(loanTerm)
    const rate = parseFloat(interestRate) / 100 / 12 // 月利率
    const totalMonths = years * 12

    let monthlyPayment, totalPayment, totalInterest

    if (repaymentMethod === 'equal-principal-interest') {
      // 等额本息
      monthlyPayment = (principal * rate * Math.pow(1 + rate, totalMonths)) / (Math.pow(1 + rate, totalMonths) - 1)
      totalPayment = monthlyPayment * totalMonths
      totalInterest = totalPayment - principal
    } else {
      // 等额本金
      const monthlyPrincipal = principal / totalMonths
      const firstMonthPayment = monthlyPrincipal + principal * rate

      totalInterest = (principal * rate * (totalMonths + 1)) / 2
      totalPayment = principal + totalInterest
      monthlyPayment = firstMonthPayment // 展示首月还款额
    }

    setResult({
      monthlyPayment: monthlyPayment.toFixed(2),
      totalPayment: totalPayment.toFixed(2),
      totalInterest: totalInterest.toFixed(2),
      isEqualPrincipalInterest: repaymentMethod === 'equal-principal-interest'
    })
  }

  return (
    <View className='loan-calculator'>
      <View className='converter-header'>
        <Text className='header-title'>贷款计算器</Text>
      </View>
      <Form>
        <Cell.Group inset title='贷款信息'>
          <Form.Item label='贷款金额'>
            <Input
              type='digit'
              placeholder='请输入贷款金额'
              value={loanAmount}
              onChange={(e) => setLoanAmount(e.detail.value)}
              rightIcon={<Text className='unit'>万元</Text>}
            />
          </Form.Item>

          <Form.Item label='贷款期限'>
            <View className='slider-container'>
              <Slider value={loanTerm} min={1} max={30} onChange={(value) => setLoanTerm(value)} />
              <Text className='slider-value'>{loanTerm}年</Text>
            </View>
          </Form.Item>

          <Form.Item label='年利率'>
            <View className='slider-container'>
              <Slider value={interestRate} min={1} max={15} step={0.1} onChange={(value) => setInterestRate(value)} />
              <Text className='slider-value'>{interestRate}%</Text>
            </View>
          </Form.Item>

          <Form.Item label='还款方式'>
            <Radio.Group value={repaymentMethod} onChange={(value) => setRepaymentMethod(value)}>
              <View className='radio-wrapper'>
                <Radio name='equal-principal-interest'>等额本息</Radio>
                <Radio name='equal-principal'>等额本金</Radio>
              </View>
            </Radio.Group>
          </Form.Item>
        </Cell.Group>
      </Form>

      <View className='calculate-btn-wrapper'>
        <Button color='primary' block size='large' onClick={calculate}>
          计算结果
        </Button>
      </View>

      <View className='result-card'>
        <View className='result-header'>
          <Text>计算结果</Text>
        </View>
        <View className='result-body'>
          {result && (
            <>
              <Cell.Group inset>
                <Cell title='月供' value={`¥${result.monthlyPayment.toFixed(2)}`} />
                <Cell title='总还款额' value={`¥${result.totalPayment.toFixed(2)}`} />
                <Cell title='总利息' value={`¥${result.totalInterest.toFixed(2)}`} />
              </Cell.Group>
              <Divider />
              <View className='tips'>
                <Text>注：以上计算结果仅供参考，实际还款金额以银行最终审批结果为准。</Text>
              </View>
            </>
          )}
        </View>
      </View>
    </View>
  )
}

export default LoanCalculator
